from flask import Flask, render_template, request, flash
import mysql.connector
import pymysql
import config

app = Flask(__name__)

app.config.from_object(config)


def create_conn_cursor():
    # conn = mysql.connector.connect(host='162.14.114.15', user='huty_ec',
    #                                passwd='foxmmer123', database='db_ec',
    #                                auth_plugin='mysql_native_password')
    conn = pymysql.connect(host='162.14.114.15', user='huty_ec',
                           password='foxmmer123', database='db_ec')
    cursor = conn.cursor()
    return conn, cursor


def save_into_mysql(data):
    conn, cursor = create_conn_cursor()
    sql = "insert into tb_word_checked (word,english_definition,chinese_translation)values(%s,%s,%s)"
    val = (data[1], data[3], data[4])
    query_sql = f"select word from tb_word_checked where word='{data[1]}'"

    cursor.execute(query_sql)
    res = cursor.fetchone()
    if res is None:
        cursor.execute(sql, val)
        conn.commit()


def query_word(word_query):
    """"
    自制简易英汉词典，带音标，中英文解释。词库内容极其庞大，应有尽有！
    """
    conn, cursor = create_conn_cursor()
    sql = f"select * from tb_maria_dict where word='{word_query}'"
    cursor.execute(sql)
    result = cursor.fetchone()
    save_into_mysql(result)
    cursor.close()
    conn.close()

    if result[3] is not None:
        en_ex = result[3].split('\\n')
        cn_ex = result[4].split('\\n')
        return result, en_ex, cn_ex
    else:
        en_ex = result[3]
        cn_ex = result[4].split('\\n')  # 这一句代码解决了大问题
        return result, en_ex, cn_ex


@app.route('/', methods=['GET', 'POST'])
def index():
    word_query = request.form.get('word_query')
    if request.method == "GET":
        return render_template('index.html')
    else:
        try:
            result, en_ex, cn_ex = query_word(word_query.strip())
            return render_template('index.html',
                                   result=result,
                                   en_ex=en_ex,
                                   cn_ex=cn_ex)
        except:
            flash('没有找到这个单词,请检查单词拼写是否正确')
            return render_template('index.html')


if __name__ == '__main__':
    app.run()
